package cn.ai.shoes.client.aop;

import cn.ai.shoes.client.entity.ComfyuiLog;
import cn.ai.shoes.client.service.ComfyuiLogService;
import cn.ai.shoes.common.exception.ServiceException;
import cn.ai.shoes.common.exception.constant.GlobalErrorCodeConstants;
import cn.ai.shoes.common.pojo.entity.CommonResult;
import cn.ai.shoes.core.pojo.entity.MyUser;
import cn.ai.shoes.core.service.UserService;
import cn.hutool.core.bean.BeanUtil;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;


@Aspect
@Component
@Slf4j
public class ComfyuiLogAspact {
    @Resource
    private ComfyuiLogService comfyuiLogService;
    @Resource
    private UserService userService;

    /**
     * 初始化
     */
    @Pointcut("@annotation(cn.ai.shoes.client.annotation.ComfyuiLogAnnotation)")
    public void imageLogAspectMethod() {
    }

    /**
     * 在方法之前执行
     */
    @Around("imageLogAspectMethod()")
    public CommonResult before(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("==================================图片日志记录切面执行========================================");
        String resultJson =null;
        Object result = new Object();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 插入数据库
        ComfyuiLog comfyuiLog = new ComfyuiLog();
        try {
            // 获取方法签名
            Signature signature = joinPoint.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            // 获取方法参数
            Object[] args = joinPoint.getArgs();
            // 用fastJson将args转换为json
            String argsJson = JSON.toJSONString(args);
            // 获取方法名
            String methodName = signature.getName();
            // 获取执行该方法人
            String username = authentication.getName();

            // 根据用户名获取用户信息
            MyUser user = userService.getOne(new LambdaQueryWrapper<MyUser>().eq(MyUser::getUsername, username));
            // 获取执行该方法人的角色
            String role = authentication.getAuthorities().iterator().next().getAuthority();

            // 获取方法注解
            Operation annotation = methodSignature.getMethod().getAnnotation(Operation.class);
            // 获取方法注解描述
            String summary = annotation.summary();
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            comfyuiLog.setUsername(username);
            comfyuiLog.setRole(role);
            comfyuiLog.setMethodName(methodName);
            comfyuiLog.setSummary(summary);
            comfyuiLog.setArgs(argsJson);
            comfyuiLog.setExcuteTime(now);
            comfyuiLog.setState("1");
            comfyuiLog.setUserId(Long.valueOf(user.getId()));
            comfyuiLog.setNickname(user.getNickname());
            //记录执行前时间戳
            long startTime = System.currentTimeMillis();
            // 获取方法返回值
            result = joinPoint.proceed();
            //记录执行后时间戳
            long endTime = System.currentTimeMillis();
            // 计算执行时间将其转换为秒
            double costTime = (endTime - startTime) / 1000.0;
            // 用fastJson将result转换为json
            resultJson = JSON.toJSONString(result);
            comfyuiLog.setCostTime(costTime);
        }catch (ServiceException e){
            throw e;
        } catch (Exception e) {
            comfyuiLog.setState("0");
            comfyuiLog.setError(e.getMessage());
            e.printStackTrace();
            throw new ServiceException(GlobalErrorCodeConstants.COMFYUI_LOG_ERROR.getResult());
        }finally {
            comfyuiLog.setResult(JSON.toJSONString(resultJson));
            comfyuiLog.setError(JSON.toJSONString(comfyuiLog.getError()));
            log.info("==================================图片日志记录切面执行结束========================================");
            new Thread(() -> {
                try {
                    comfyuiLogService.save(comfyuiLog);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
        CommonResult commonResult = BeanUtil.toBean(result, CommonResult.class);
        return commonResult;
    }
}
